package com.starsea.book.ui.newpage

import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.ActivityMsgBinding
import com.starsea.book.ui.newpage.adapter.MyPagerAdapter
import com.starsea.book.ui.newpage.viewmodel.MsgViewModel
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding

/**
 * @author Lee
 * @createTime 2024-01-10 10 GMT+8
 * @desc : 我的消息
 */
class MsgActivity : VMBaseActivity<ActivityMsgBinding, MsgViewModel>() {
    override val binding by viewBinding(ActivityMsgBinding::inflate)
    override val viewModel by viewModels<MsgViewModel>()

    val mFragments: MutableList<Fragment> = ArrayList()

    var myPagerAdapter: MyPagerAdapter? = null

    val listTitle: MutableList<String> = ArrayList()

    var index = 0

    override
    fun onActivityCreated(savedInstanceState: Bundle?) {

        setTitle(R.string.title_msg)

        viewModel.getMsgType()

        viewModel.msgTypeResult.observe(this) {
            if (it.status == 200) {

                listTitle.clear()
                mFragments.clear()
                it.data!!.forEachIndexed { index, msgTypeEntity ->
                    listTitle.add(msgTypeEntity.name ?: "")
                    mFragments.add(
                        MsyFragment.newInstance(
                            msgTypeEntity.code,
                            msgTypeEntity.name ?: ""
                        )
                    )
                }

                if (myPagerAdapter == null)
                    myPagerAdapter = MyPagerAdapter(supportFragmentManager, mFragments, listTitle)

                binding.vpContent.offscreenPageLimit = listTitle.size
                binding.vpContent.adapter = myPagerAdapter
                binding.stlTab.setViewPager(binding.vpContent)
                binding.vpContent.currentItem = index

                it.data!!.forEachIndexed { index, msgTypeEntity ->
                    if (msgTypeEntity.number != 0) {
                        binding.stlTab.showMsg(index, msgTypeEntity.number)
                    } else {
                        binding.stlTab.hideMsg(index)
                    }
                }
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this@MsgActivity)
            } else {
                toastOnUi(it.msg)
            }
        }
    }

    override fun setTitle(resId: Int) {
        super.setTitle(resId)
        binding.titleBar.setTitle(resId)
    }

}